package com.Linngdu664.drglaserpointer.client.render;

import com.mojang.blaze3d.systems.RenderSystem;
import com.mojang.blaze3d.vertex.*;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GameRenderer;
import net.minecraft.world.phys.Vec3;
import net.minecraftforge.client.event.RenderLevelStageEvent;

public class LaserRenderer {
    public static void drawLine(RenderLevelStageEvent event, Vec3 start, Vec3 end, int r, int g, int b) {
        RenderSystem.depthMask(false);
        RenderSystem.disableCull();
        RenderSystem.enableBlend();
        RenderSystem.defaultBlendFunc();
        RenderSystem.disableTexture();
        Vec3 rVec = end.subtract(start);
        Vec3 n1 = rVec.cross(new Vec3(0, 1, 0));
        if (n1.lengthSqr() < 1e-10) {
            n1 = rVec.cross(new Vec3(1, 0, 0));
        }
        n1 = n1.normalize().scale(0.001);
        Vec3 n2 = rVec.cross(n1).normalize().scale(0.001);
        BufferBuilder bufferBuilder = Tesselator.getInstance().getBuilder();
        bufferBuilder.begin(VertexFormat.Mode.QUADS, DefaultVertexFormat.POSITION_COLOR);
        drawQuad(bufferBuilder, start, end, n1, r, g, b);
        drawQuad(bufferBuilder, start, end, n2, r, g, b);
        bufferBuilder.end();
        VertexBuffer vertexBuffer = new VertexBuffer();
        vertexBuffer.bind();
        vertexBuffer.upload(bufferBuilder);
        PoseStack poseStack = event.getPoseStack();
        poseStack.pushPose();
        Vec3 view = Minecraft.getInstance().gameRenderer.getMainCamera().getPosition();
        poseStack.translate(-view.x, -view.y, -view.z);
        vertexBuffer.drawWithShader(poseStack.last().pose(), event.getProjectionMatrix().copy(), GameRenderer.getPositionColorShader());
        poseStack.popPose();
        VertexBuffer.unbind();
        RenderSystem.depthMask(true);
        RenderSystem.enableCull();
        RenderSystem.disableBlend();
        RenderSystem.enableTexture();
    }

    private static void drawQuad(BufferBuilder bufferBuilder, Vec3 start, Vec3 end, Vec3 n, int r, int g, int b) {
        Vec3 start1 = start.add(n);
        Vec3 start2 = start.subtract(n);
        Vec3 end1 = end.add(n);
        Vec3 end2 = end.subtract(n);
        bufferBuilder.vertex(start1.x, start1.y, start1.z).color(r, g, b, 255).endVertex();
        bufferBuilder.vertex(start2.x, start2.y, start2.z).color(r, g, b, 255).endVertex();
        bufferBuilder.vertex(end2.x, end2.y, end2.z).color(r, g, b, 255).endVertex();
        bufferBuilder.vertex(end1.x, end1.y, end1.z).color(r, g, b, 255).endVertex();
    }
}
